package com.wjk.easy.ui;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.android.hdhe.uhf.reader.WeightReader;
import com.clj.fastble.data.BleDevice;
import com.google.android.material.navigation.NavigationView;
import com.wjk.easy.R;
import com.wjk.easy.blue.ConnectBlueCallBack;
import com.wjk.easy.blue.ConnectBlueTask;
import com.wjk.easy.blue.FastBleService;
import com.wjk.easy.blue.PinBlueCallBack;
import com.wjk.easy.blue.PinBlueReceiver;
import com.wjk.easy.blue.rd915demo.BluetoothLeService;
import com.wjk.easy.blue.rd915demo.UhfService;
import com.wjk.easy.data.LoginDataSource;
import com.wjk.easy.blue.FastBleDeviceManager;
import com.wjk.easy.ui.login.ForgetPwdActivity;
import com.wjk.easy.ui.login.LoginActivity;
import com.wjk.easy.utils.CommonUtil;
import com.wjk.easy.utils.Lunar;
import com.wjk.easy.view.BlueScanListDialog;

import java.util.Calendar;
import java.util.Date;

import static com.wjk.easy.blue.FastBleService.DEVICE_TYPE_UHF;
import static com.wjk.easy.blue.FastBleService.DEVICE_TYPE_WEIGHT;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,View.OnClickListener {
    private static final int MSG_BLUETOOTH_NOT_SUPPORT = 45;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 33:
                    Toast.makeText(MainActivity.this, (String) msg.obj,Toast.LENGTH_SHORT).show();
                    break;
                case 20:
                    Toast.makeText(MainActivity.this, "thread is running",Toast.LENGTH_SHORT).show();
                    break;
                case MSG_BLUETOOTH_NOT_SUPPORT:
                    Toast.makeText(MainActivity.this, "当前终端不支持蓝牙BLE，请更换",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };
    private TextView tv_state_uhf;
    private TextView tv_state_weight;
    //private TextView tv_state_ruler;


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
        initDrawerHead(navigationView);
        findViewById(R.id.tv_go_work).setOnClickListener(this);
        tv_state_uhf = findViewById(R.id.tv_state_uhf);
        tv_state_weight = findViewById(R.id.tv_state_weight);
        tv_state_weight.setOnClickListener(this);
        tv_state_uhf.setOnClickListener(this);

        if(savedInstanceState!=null){
            tv_state_weight.setSelected( savedInstanceState.getBoolean("tv_state_weight"));
            tv_state_uhf.setSelected(savedInstanceState.getBoolean("tv_state_uhf"));
        }
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        IntentFilter filter4 = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        IntentFilter filter5 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        IntentFilter filter6 = new IntentFilter("com.wjk.easy.BluetoothDevice.ACTION_BOND_STATE_CHANGED");
        registerReceiver(pinBlueReceiver,filter4);
        registerReceiver(pinBlueReceiver,filter5);
        registerReceiver(pinBlueReceiver,filter6);
        Intent intent=new Intent(this, UhfService.class);
        startService(intent);
    }

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        return intentFilter;
    }


    PinBlueReceiver pinBlueReceiver = new PinBlueReceiver(new PinBlueCallBack() {
        @Override
        public void onBondRequest() {
            Toast.makeText(MainActivity.this,"开始配对",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBondSuccess(BluetoothDevice device) {
            Toast.makeText(MainActivity.this,"配对成功",Toast.LENGTH_SHORT).show();
            new ConnectBlueTask(new ConnectBlueCallBack() {
                @Override
                public void onStartConnect() {
                    Toast.makeText(MainActivity.this,"开始连接",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onConnectSuccess(BluetoothDevice bluetoothDevice, BluetoothSocket bluetoothSocket) {
                    Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
                    tv_state_weight.setSelected(true);
                    PinBlueReceiver.bluetoothSocket = bluetoothSocket;
                }

                @Override
                public void onConnectFail(BluetoothDevice bluetoothDevice, String errMsg) {
                    Toast.makeText(MainActivity.this,"连接失败："+errMsg,Toast.LENGTH_SHORT).show();
                }
            }).execute(device);
        }

        @Override
        public void onBonding(BluetoothDevice device) {

        }

        @Override
        public void onBondFail(BluetoothDevice device) {
            Toast.makeText(MainActivity.this,"配对失败",Toast.LENGTH_SHORT).show();
        }
    });
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                //uhf 连接成功
                tv_state_uhf.setSelected(true);
                Toast.makeText(MainActivity.this,"读卡器连接成功！",Toast.LENGTH_SHORT).show();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                //uhf 断开
                Toast.makeText(MainActivity.this,"读卡器已断开！",Toast.LENGTH_SHORT).show();
                tv_state_uhf.setSelected(false);
            }
        }
    };

    @Override
    protected void onRestart() {
        super.onRestart();
        tv_state_uhf.setSelected(UhfService.isConnectiing());
        if(PinBlueReceiver.bluetoothSocket!=null){
            tv_state_weight.setSelected(PinBlueReceiver.bluetoothSocket.isConnected());
        }else{
            tv_state_weight.setSelected(false);
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putBoolean("tv_state_uhf",tv_state_uhf.isSelected());
        outState.putBoolean("tv_state_weight",tv_state_weight.isSelected());
        //outState.putBoolean("tv_state_ruler",tv_state_ruler.isSelected());
        super.onSaveInstanceState(outState);
    }

    FastBleService.LocalBinder mBlueServiceBinder;
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_state_uhf:
                if(tv_state_uhf.isSelected()){
                    return;
                }
                showDeviceScanListDialog(DEVICE_TYPE_UHF);
                break;
            case R.id.tv_state_weight:
                if(tv_state_weight.isSelected()){
                    return;
                }
                showDeviceScanListDialog(DEVICE_TYPE_WEIGHT);
                break;
            case R.id.tv_go_work:
                if(isAllDeviceReady()){
                    startActivity(new Intent(MainActivity.this, ExamActivity.class));
                }else{
                    Toast.makeText(this,"外设尚未准备就绪，请确认",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    private boolean isAllDeviceReady(){
        return //tv_state_uhf.isSelected()&&
                tv_state_weight.isSelected();
    }


    private void showDeviceScanListDialog(String deviceType) {
        FastBleDeviceManager manager = new FastBleDeviceManager();;
        //判断蓝牙是否支持
        if(!manager.isSupportBle()){
            mHandler.obtainMessage(MSG_BLUETOOTH_NOT_SUPPORT).sendToTarget();
            return;
        }
        //判断蓝牙是否打开
        if(manager.isBleOpen()){
            dialog = new BlueScanListDialog(this,deviceType);
            dialog.show();
        }else{
            manager.openBluetooth();
        }
    }


    BlueScanListDialog dialog;
    WeightReader weightReader;
    private void initDrawerHead(NavigationView nav){
        Calendar calendar= Calendar.getInstance();
        Lunar lunar = new Lunar(calendar);
        String lunarStr = lunar.toString();
        String now  = CommonUtil.dateToStr(new Date(),"yyyy-MM-dd");
        TextView nav_header_sub_title = nav.getHeaderView(0).findViewById(R.id.nav_header_sub_title);
        nav_header_sub_title.setText(getString(R.string.nav_header_subtitle,now,lunarStr));
        String userName = getIntent().getStringExtra("lastUserName");
        TextView nav_header_title = nav.getHeaderView(0).findViewById(R.id.nav_header_title);
        nav_header_title.setText(getString(R.string.nav_header_title,userName));
    }

    @Override
    protected void onDestroy() {
        Log.i("wjk","main destory");
        if(dialog!=null&&dialog.isShowing()){
            dialog.dismiss();
        }
        super.onDestroy();
        if(weightReader!=null) {
            weightReader.close();
        }
        unregisterReceiver(mGattUpdateReceiver);
        //unbindService(bleServiceConnection);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(weightReader!=null)weightReader.close();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id){
            case R.id.action_settings:
                return true;
            case R.id.action_logout:
                doLogout();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void doLogout() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        LoginDataSource loginDataSource = new LoginDataSource();
        loginDataSource.logout();
        finish();
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_data:
                startActivity(new Intent(this, DataManageActivity.class));
                break;
            case R.id.nav_exam:
                startActivity(new Intent(this, ExamManageActivity.class));
                break;
            case R.id.nav_setting:
                break;
            case R.id.nav_logout:
                doLogout();
                break;
            case R.id.nav_pwd_reset:
                startActivity(new Intent(this, ForgetPwdActivity.class));
                break;
        }
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
            return super.dispatchKeyEvent(event);
        }
        return true;
    }
}
